(function (window, lib) {
    const document = window.document;
    const documentElement = document.documentElement;
    const viewportMeta = document.querySelector('meta[name="viewport"]');
    const flexibleMeta = document.querySelector('meta[name="flexible"]');
    const flexible = lib.flexible || (lib.flexible = {});
    let dpr = 0;
    let scale = 0;

    // 设置视口和根字体大小
    function setViewport() {
        let width = documentElement.getBoundingClientRect().width;
        const maxWidth = 540;

        // 限制最大宽度
        if (width / dpr > maxWidth) {
            width = maxWidth * dpr;
        }

        // 计算 rem 基准值
        const rem = width / 10;
        flexible.rem = window.rem = rem;
    }

    // 如果存在 viewport meta 标签，则读取缩放比例
    if (viewportMeta) {
        console.warn("Using existing meta tag to set scale ratio");
        const match = viewportMeta.getAttribute("content").match(/initial\-scale=([\d\.]+)/);
        if (match) {
            scale = parseFloat(match[1]);
            dpr = parseInt(1 / scale);
        }
    } else if (flexibleMeta) {
        // 如果存在 flexible meta 标签，则读取 dpr 和缩放比例
        const content = flexibleMeta.getAttribute("content");
        if (content) {
            const initialDprMatch = content.match(/initial\-dpr=([\d\.]+)/);
            const maximumDprMatch = content.match(/maximum\-dpr=([\d\.]+)/);
            if (initialDprMatch) {
                dpr = parseFloat(initialDprMatch[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
            if (maximumDprMatch) {
                dpr = parseFloat(maximumDprMatch[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
        }
    }

    // 如果没有设置 dpr 和缩放比例，则根据设备信息进行设置
    if (!dpr && !scale) {
        const isAndroid = window.navigator.appVersion.match(/android/gi);
        const isIPhone = window.navigator.appVersion.match(/iphone/gi);
        const devicePixelRatio = window.devicePixelRatio;

        if (isIPhone) {
            dpr = devicePixelRatio >= 3 ? 3 : devicePixelRatio >= 2 ? 2 : 1;
        } else {
            dpr = 1;
        }
        scale = 1 / dpr;
    }

    // 设置 data-dpr 属性
    documentElement.setAttribute("data-dpr", dpr);

    // 如果没有 viewport meta 标签，则创建一个
    if (!viewportMeta) {
        const meta = document.createElement("meta");
        meta.setAttribute("name", "viewport");
        meta.setAttribute("content", `initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no`);
        if (documentElement.firstElementChild) {
            documentElement.firstElementChild.appendChild(meta);
        } else {
            const wrapper = document.createElement("div");
            wrapper.appendChild(meta);
            document.write(wrapper.innerHTML);
        }
    }

    // 初始化视口和根字体大小
    setViewport();

    // 将 dpr 和 rem 相关的函数挂载到 flexible 对象上
    flexible.dpr = window.dpr = dpr;
    flexible.refreshRem = setViewport;
    flexible.rem2px = function (value) {
        const remValue = parseFloat(value) * this.rem;
        return typeof value === "string" && value.match(/rem$/) ? `${remValue}px` : remValue;
    };
    flexible.px2rem = function (value) {
        const remValue = parseFloat(value) / this.rem;
        return typeof value === "string" && value.match(/px$/) ? `${remValue}rem` : remValue;
    };

    // 动态设置 daan-novel-content 的 column-width 和 height
    function setDaanNovelContentStyles() {
        const contentElement = document.querySelector('.daan-novel-content');
        if (contentElement) {
            const padding = 0.5 * flexible.rem; // 0.3125rem 转换为 px
            const viewportWidth = window.innerWidth;

            // 设置 column-width 为视口宽度减去内边距
            const columnWidth = viewportWidth - 2 * padding;
            contentElement.style.columnWidth = `${columnWidth}px`;
        }
    }

    // 初始化设置
    setDaanNovelContentStyles();

    // 监听窗口大小变化事件，重新计算样式
    window.addEventListener("resize", () => {
        clearTimeout(flexible.tid);
        flexible.tid = setTimeout(setDaanNovelContentStyles, 300);
    }, false);

    // 监听页面显示事件，重新计算样式
    window.addEventListener("pageshow", (event) => {
        if (event.persisted) {
            clearTimeout(flexible.tid);
            flexible.tid = setTimeout(setDaanNovelContentStyles, 300);
        }
    }, false);

})(window, window.lib || (window.lib = {}));
